package com.zlll.winner.service.weixin;

import com.alibaba.fastjson.JSONObject;
import com.zlll.winner.business.service.common.IRedisService;
import com.zlll.winner.business.service.weixin.IWxToolsService;
import com.zlll.winner.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;


/**
 * 微信相关工具类
 */
@Service
@Slf4j
public class WxToolsServiceImpl implements IWxToolsService {

    @Value("${wx.weapp.appid}")
    private String appId;

    @Value("${wx.weapp.secret}")
    private String secret;

    @Autowired
    private IRedisService redisService;



    /**
     * 获取小程序AppId
     *
     * @return
     */
    @Override
    public String getAppId() {
        return appId;
    }

    /**
     * 获取小程序secret
     *
     * @return
     */
    @Override
    public String getSecret() {
        return secret;
    }

    public String getAccessToken(Boolean refresh){
        String token = redisService.getRedisByString("" + appId);
        if (!StringUtils.isNotBlank(token) || refresh) {
            String tokenResp = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret, null);
            log.info("微信接口token 参数：appId:{},secret:{},结果：{}", appId, secret, tokenResp);
            JSONObject res = JSONObject.parseObject(tokenResp);
            if (res != null) {
                token = res.getString("access_token");
//                Integer expiresTime = res.getInteger("expires_in");
                redisService.setRedisByString(appId + secret, token, 1800);
            }
        }
        return token;
    }

}
